// 关于用户操作的接口API函数

import request, { baseURL } from '@/utils/request'
import axios from 'axios'

/**
 * 短信登录
 * @param {String} mobile - 手机号
 * @param {String} code - 验证码
 * @returns Promise
 */
export const userLogin = ({ mobile, code }) => {
  return request({
    url: '/v1_0/authorizations',
    method: 'post',
    data: { mobile, code }
  })
}

/**
 * 发送短信验证码
 * @param {String} mobile - 手机号
 * @returns Promise
 */
export const sendMessage = (mobile) => {
  return request({ url: '/v1_0/sms/codes/' + mobile })
}

/**
 * 关注，取消关注
 * @param {String} authorId - 作者ID（用户ID）
 * @param {Boolean} isFollow - 是关注，还是取消关注
 */
export const followAuthor = (authorId, isFollow) => {
  if (isFollow) {
    // 关注
    return request({
      url: '/v1_0/user/followings',
      method: 'post',
      data: { target: authorId }
    })
  } else {
    // 取消关注
    return request({
      url: '/v1_0/user/followings/' + authorId,
      method: 'delete'
    })
  }
}

/**
 * 获取用户信息（用于个人中心首页）
 * @returns
 */
export const getUserInfo = () => {
  return request({
    url: '/v1_0/user'
  })
}

/**
 * 获取用户信息（用于编辑资料页面）
 * @returns
 */
export const getUserProfile = () => {
  return request({
    url: '/v1_0/user/profile'
  })
}

/**
 * 修改用户头像
 * @param {Object} formData - formData对象，包含字段 photo
 * @returns
 */
export const updateUserPhoto = (formData) => {
  return request({
    url: '/v1_0/user/photo',
    method: 'patch',
    data: formData
  })
}

/**
 * 修改用户资料
 * @param {Object} user - 用户资料对象 {name:'xxx'} {gender:1} {birthday: '2010-10-11'}
 */
export const updateUserProfile = (user) => {
  return request({
    url: '/v1_0/user/profile',
    method: 'patch',
    data: user
  })
}

/**
 * 刷新token
 * @param {String} refreshToken - 保存的refresh_token
 * @returns
 */
export const refreshTokenAPI = (refreshToken) => {
  return axios({
    url: baseURL + 'v1_0/authorizations',
    method: 'put',
    headers: {
      Authorization: `Bearer ${refreshToken}`
    }
  })
}
